package de.fhhannover.inform.itteam.snmpnetviz.gui;

import java.awt.Dimension;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import prefuse.Display;
import prefuse.Visualization;
import prefuse.util.GraphicsLib;
import prefuse.util.display.DisplayLib;

public class NVFrame extends JFrame {
	private static final long serialVersionUID = -216264154974368869L;
	private Display display;
	private JLayeredPane layeredPane;
	private ControlPanel controlPanel;
	private KeyPanel keyPanel;
	private int resX, resY;
	
	public NVFrame(int x, int y, final Display display) {
		this.setTitle("SNMP - Network Viewer");
		this.setSize(x, y);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		resX = x;
		resY = y;
		
		this.display = display;
		
		// set look and feel
		try {
		    // Set System Look and Feel
	        UIManager.setLookAndFeel(
	            UIManager.getSystemLookAndFeelClassName());
	    } 
	    catch (UnsupportedLookAndFeelException e) {
	    	System.err.println(">>	No look-and-feel support for this plattform!");
	    	e.printStackTrace();
	    }
	    catch (Exception e) {
	       e.printStackTrace();
	    }
		
		initComponents(display);
	}
	
	private void initComponents(Display display) {
		// set layout
		layeredPane = new JLayeredPane();
		layeredPane.setPreferredSize(new Dimension(resX, resY));

//		// visualization 
        display.setBounds(0, 0, resX, resY);
		Visualization viz = getVisualization();
		viz.run("color");
		viz.run("layout");
		try {
			int delay = 2000;
			Thread.sleep(delay);
			
			if ( !display.isTranformInProgress() )
	        {
	            Rectangle2D bounds = viz.getBounds(Visualization.ALL_ITEMS);
	            int margin = 50;
				GraphicsLib.expand(bounds, margin + (int)(1/display.getScale()));
	            DisplayLib.fitViewToBounds(display, bounds, delay);
	        }
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
    	
		layeredPane.add(display, new Integer(1));
		
//		// key panel
		keyPanel = new KeyPanel(this);
		int kpX = keyPanel.getWidth();
		int kpY = keyPanel.getHeight();
		int leftBorder = resX - Math.round(kpX*1.1f);
		keyPanel.setBounds(leftBorder, Math.round(resY/40), kpX, kpY);
		layeredPane.add(keyPanel, new Integer(2));
			
//		// button panel
		controlPanel = new ControlPanel(this, keyPanel);
		int cpX = controlPanel.getPreferredSize().width;
		int cpY = controlPanel.getPreferredSize().height;
		controlPanel.setBounds(leftBorder, resY - Math.round(cpY*1.2f), cpX, cpY);
		layeredPane.add(controlPanel, new Integer(3));
		
		this.add(layeredPane);
		layeredPane.revalidate();
	}
	
	public Visualization getVisualization() {
		if (display != null)
			return display.getVisualization();
		
		return null;
	}

}
